<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="元素名称" prop="elementName">
        <el-input v-model="queryParams.elementName" placeholder="请输入元素名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="元素类型" prop="elementType">
        <el-select v-model="queryParams.elementType" placeholder="请选择元素类型" clearable>
          <el-option v-for="dict in ds_element_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['datascreen:element:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['datascreen:element:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['datascreen:element:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="elementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="元素编号" align="center" prop="elementId" v-if="true" />
      <el-table-column label="元素名称" align="center" prop="elementName" />
      <el-table-column label="元素类型" align="center" prop="elementType">
        <template #default="scope">
          <dict-tag :options="ds_element_type" :value="scope.row.elementType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleDesign(scope.row)"
            v-hasPermi="['datascreen:element:edit']">设计</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['datascreen:element:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['datascreen:element:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改大屏元素对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="elementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="元素名称" prop="elementName">
          <el-input v-model="form.elementName" placeholder="请输入元素名称" />
        </el-form-item>
        <el-form-item label="元素编码" prop="elementCode">
          <el-input v-model="form.elementCode" placeholder="请输入元素编码" />
        </el-form-item>
        <el-form-item label="元素类型" prop="elementType">
          <el-select v-model="form.elementType" placeholder="请选择元素类型">
            <el-option v-for="dict in ds_element_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设计大屏元素 -->
    <el-dialog :title="title" v-model="openDesign" width="500px" :fullscreen="true" destroy-on-close append-to-body>
      <el-row>
        <el-col :span="12">
          <el-form ref="elementDesignRef" :model="form" :rules="rulesDesign" label-width="100px">
            <el-form-item label="大标题" prop="titleText">
              <el-input v-model="form.titleText" placeholder="请输入大标题" style="width: 220px" />
            </el-form-item>
            <el-form-item label="副标题" prop="titleSubtext">
              <el-input v-model="form.titleSubtext" placeholder="请输入副标题" style="width: 220px" />
            </el-form-item>
            <el-form-item label="标题位置" prop="titleLeft">
              <el-radio-group v-model="form.titleLeft">
                <el-radio v-for="dict in ds_position" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-space fill>
              <el-alert type="info" show-icon :closable="false">
                <p>数据项：数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。</p>
                <p>坐标轴：坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用。</p>
              </el-alert>
              <el-form-item label="提示框" prop="tooltip">
                <el-switch v-model="form.tooltip" active-text="显示" inactive-text="隐藏" />
              </el-form-item>
            </el-space>
            <el-form-item label="图列" v-show="'scatterplot' != form.elementType" prop="legend">
              <el-switch v-model="form.legend" active-text="显示" inactive-text="隐藏" />
            </el-form-item>
            <el-form-item label="图列位置" v-show="'scatterplot' != form.elementType" prop="legendLeft" v-if="form.legend">
              <el-radio-group v-model="form.legendLeft">
                <el-radio v-for="dict in ds_position" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="数据来源" prop="elementDataSources">
              <el-radio-group v-model="form.elementDataSources">
                <el-radio v-for="dict in ds_data_sources" :key="dict.value" :label="dict.value">{{ dict.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <span v-if="'custom' == form.elementDataSources">
              <el-form-item label="自定义数据集" prop="customId">
                <el-select v-model="form.customId" placeholder="请选择">
                  <el-option
                    v-for="item in customDataList"
                    :key="item.customId"
                    :label="item.customName"
                    :value="item.customId"
                  />
                </el-select>
              </el-form-item>
            </span>
            <span v-if="'model' == form.elementDataSources">
              <el-form-item label="模型" prop="elementModel">
                <el-select v-model="form.elementModel" filterable remote reserve-keyword placeholder="请输入模型名称"
                  remote-show-suffix :remote-method="xModelRemoteMethod" :loading="xModelIdLoading"
                  @change="HandleXModelChange">
                  <el-option v-for="item in selectXModelList" :key="item.modelId" :label="item.modelName"
                    :value="item.modelId" />
                </el-select>
              </el-form-item>
              <el-form-item label="类别字段" v-show="'scatterplot' != form.elementType" prop="exField">
                <el-select v-model="form.exField" placeholder="请选择">
                  <el-option v-for="item in selectXFieldList" :key="item.fieldId" :label="item.remark"
                    :value="item.fieldId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="显示名称字段" v-show="'scatterplot' == form.elementType" prop="exField">
                <el-select v-model="form.exField" placeholder="请选择">
                  <el-option v-for="item in selectYFieldList" :key="item.fieldId" :label="item.remark"
                    :value="item.fieldId"></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="类别单位名称" prop="exName">
                <el-input v-model="form.exName" placeholder="请输入类别单位名称" style="width: 220px" />
              </el-form-item> -->
              <span v-show="'pie' != form.elementType && 'scatterplot' != form.elementType">
                <el-form-item label="数据字段" prop="eyData" style="display: flex;">
                  <div v-for="(data, index) in form.eyDataList" style="margin-bottom: 5px;">
                    <el-select v-model="data.statisticsType" placeholder="请选择统计类型">
                      <el-option v-for="dict in ds_statistics_type" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                    </el-select>
                    &nbsp;&nbsp;
                    <el-select v-model="data.eyField" placeholder="请选择字段">
                      <el-option v-for="item in selectYFieldList" :key="item.fieldId" :label="item.remark"
                        :value="item.fieldId"></el-option>
                    </el-select>
                    &nbsp;&nbsp;
                    <span>
                      <el-button type="primary" icon="Plus" circle @click="addEyData" />
                      <el-button type="danger" icon="Delete" circle @click="deleteEyData(index)" />
                    </span>
                  </div>
                </el-form-item>
              </span>
              <span v-show="'scatterplot' == form.elementType">
                <el-form-item label="x轴字段" prop="eyxField">
                  <el-select v-model="form.eyxField" placeholder="请选择">
                    <el-option v-for="item in selectYFieldList" :key="item.fieldId" :label="item.remark"
                      :value="item.fieldId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="y轴字段" prop="eyyField">
                  <el-select v-model="form.eyyField" placeholder="请选择">
                    <el-option v-for="item in selectYFieldList" :key="item.fieldId" :label="item.remark"
                      :value="item.fieldId"></el-option>
                  </el-select>
                </el-form-item>
              </span>
            </span>
          </el-form>
        </el-col>
        <el-col :span="12" class="design-right">
          <div v-show="designInfoOpen" style="width: 100%;">
            <DatascreenElement :elementId="elementId" :key="datascreenElementKey" />
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-row>
            <el-col :span="12">
              <el-button :loading="buttonLoading" type="success" @click="submitView">预 览</el-button>
            </el-col>
            <el-col :span="12">
              <el-button :loading="buttonLoading" type="primary" @click="designSubmitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Element">
import { listElement, getElement, delElement, addElement, updateElement, 
  getElementForUpdate, getElementForEcharts } from "@/api/datascreen/element";
import { listAllCustomData, getCustomData } from "@/api/datascreen/customData";
import { queryFieldList } from "@/api/lowcode/field";
import { queryModelList } from "@/api/lowcode/model";
// import Histogram from "@/views/echarts/Histogram.vue";
// import LineChart from "@/views/echarts/LineChart.vue";
// import Pie from "@/views/echarts/Pie.vue"
// import DatascreenElement from "@/components/DatascreenElement"

const { proxy } = getCurrentInstance();
const {
  ds_element_type,
  sys_normal_disable,
  ds_prompt_box,
  ds_position,
  ds_statistics_type,
  ds_data_sources
} = proxy.useDict(
  'ds_element_type',
  'sys_normal_disable',
  'ds_prompt_box',
  'ds_position',
  'ds_statistics_type',
  'ds_data_sources'
);

const elementList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openDesign = ref(false)
const xModelIdLoading = ref(false)
const selectXModelList = ref([])
const selectXFieldList = ref([])
const selectYFieldList = ref([])
const chartData = ref(undefined)
const customDataList = ref([])
const designInfoOpen = ref(false)
const elementId = ref(null)
const datascreenElementKey = ref(false)
const updateElementInfo = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elementName: undefined,
    elementType: undefined,
    status: undefined,
  },
  rules: {
    elementId: [
      { required: true, message: "元素编号不能为空", trigger: "blur" }
    ],
    elementName: [
      { required: true, message: "元素名称不能为空", trigger: "blur" }
    ],
    elementCode: [
      { required: true, message: "元素编码不能为空", trigger: "blur" }
    ],
    elementType: [
      { required: true, message: "元素类型不能为空", trigger: "change" }
    ]
  },
  rulesDesign: {
    elementDataSources: [
      { required: true, message: "数据来源不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules, rulesDesign } = toRefs(data);

/** 查询大屏元素列表 */
function getList() {
  loading.value = true;
  listElement(queryParams.value).then(response => {
    elementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取自定义数据集列表 */
function getCustomDataList(){
  listAllCustomData({ status: '0' }).then(response => {
    customDataList.value = response.data
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  openDesign.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    elementId: null,
    elementName: null,
    elementCode: null,
    elementType: null,
    elementDataSources: '0',
    titleText: null,
    titleSubtext: null,
    titleLeft: 'center',
    tooltip: null,
    legend: null,
    legendLeft: 'left',
    elementModel: null,
    exField: null,
    exName: null,
    statisticsType: null,
    eyDataList: [{
      statisticsType: undefined,
      eyField: undefined
    }],
    eyName: null,
    status: '0',
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("elementRef");
  proxy.resetForm("elementDesignRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.elementId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加大屏元素";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  selectXModelList.value = []
  selectXFieldList.value = []
  selectYFieldList.value = []
  const _elementId = row.elementId || ids.value
  getElementForUpdate(_elementId).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改大屏元素";
  });
}

/** 设计按钮操作 */
function handleDesign(row) {
  loading.value = true
  updateElementInfo.value = {}
  reset();
  designInfoOpen.value = false
  selectXModelList.value = []
  selectXFieldList.value = []
  selectYFieldList.value = []
  getElement(row.elementId).then(response => {
    loading.value = false;
    form.value = response.data;
    selectXModelList.value = response.data.modelVoList
    selectXFieldList.value = response.data.exFieldVoList
    selectYFieldList.value = response.data.eyFieldVoList
    if (!form.value.eyData) {
      form.value.eyDataList = []
      form.value.eyDataList.push({
        statisticsType: undefined,
        eyField: undefined
      })
    } else {
      form.value.eyDataList = JSON.parse(form.value.eyData)
    }
    openDesign.value = true
    title.value = "设计大屏元素";
  });
}

/** 预览操作 */
function submitView() {
  if('custom' == form.value.elementDataSources){
    if(!form.value.customId){
      proxy.$modal.msgError('请选择自定义数据集');
      return
    }
    // getCustomData(form.value.customId).then(response => {
    //   let chart = {}
    //   chart.seriesName = response.data.customName
    //   chart.yAxis = response.data.typeDataList
    //   chart.series = response.data.dataDataList
    //   chart.element = form.value
    //   chartData.value = chart
    // })
  }

  if('model' == form.value.elementDataSources){
    if(!form.value.exField){
      proxy.$modal.msgError('模型数据不完整');
      return
    }
  }

  form.value.eyData = JSON.stringify(form.value.eyDataList)
  proxy.$refs["elementDesignRef"].validate(valid => {
    if(updateElementInfo.value == JSON.stringify(form.value)){
      return
    }
    updateElementInfo.value = JSON.stringify(form.value)
    buttonLoading.value = true;
    if (form.value.elementId != null) {
      updateElement(form.value).then(response => {
        elementId.value = form.value.elementId
        designInfoOpen.value = true
        datascreenElementKey.value = !datascreenElementKey.value
      }).finally(() => {
        buttonLoading.value = false;
      });
    }
  });
  
  // getElementForEcharts(form.value.elementId).then(response => {
  //   let chart = {}
  //   chart.seriesName = response.data.seriesName
  //   chart.yAxis = response.data.yAxis
  //   chart.series = response.data.series
  //   chart.element = form.value
  //   chartData.value = chart

  // })
}

/** x轴模型 */
function xModelRemoteMethod(keyword) {
  if (!keyword) {
    return
  }
  queryModelList({ modelName: keyword }).then(response => {
    selectXModelList.value = response.data
  })
}

/** x轴模型选中事件 */
function HandleXModelChange() {
  form.value.exField = undefined
  form.value.eyDataList = []
  form.value.eyDataList.push({
    statisticsType: undefined,
    eyField: undefined
  })
  queryFieldList({ modelId: form.value.elementModel, dictionaryId: 1 }).then(response => {
    selectXFieldList.value = response.data
  })
  queryFieldList({ modelId: form.value.elementModel }).then(response => {
    selectYFieldList.value = response.data
  })
}

/** 添加数据字段 */
function addEyData() {
  form.value.eyDataList.push({
    statisticsType: undefined,
    eyField: undefined
  })
}

/** 删除数据字段 */
function deleteEyData(index) {
  if (form.value.eyDataList.length > 1) {
    form.value.eyDataList.splice(index, 1);
  }
}

/** 设计提交按钮 */
function designSubmitForm() {
  form.value.eyData = JSON.stringify(form.value.eyDataList)
  proxy.$refs["elementDesignRef"].validate(valid => {
    if(updateElementInfo.value == JSON.stringify(form.value)){
      proxy.$modal.msgSuccess("修改成功");
      openDesign.value = false;
      getList();
      return
    }
    buttonLoading.value = true;
    if (form.value.elementId != null) {
      updateElement(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        openDesign.value = false;
        getList();
      }).finally(() => {
        buttonLoading.value = false;
      });
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["elementRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.elementId != null) {
        updateElement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addElement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _elementIds = row.elementId || ids.value;
  proxy.$modal.confirm('是否确认删除大屏元素编号为"' + _elementIds + '"的数据项？').then(function () {
    loading.value = true;
    return delElement(_elementIds);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

getCustomDataList();
getList();
</script>

<style lang='scss' scoped>
  .design-right{
    display: flex;
    align-items: center;
  }
</style>
